%% @author Administrator
%% @doc @todo Add description to http_svr.


-module(http_svr).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-include("log.hrl").

-export([start_link/0,test/0]).



-record(state, {}).

start_link() ->
	gen_server:start_link({global, ?MODULE}, ?MODULE, [], []).

init([]) -> 
	?debug("http_svr_init"),
	start_http(),
	start_http_client(), 
	timer:apply_after(2000, gen_server, cast, [{global,agent_mng}, {http_svr_init,self()}]),
	timer:apply_after(2000, gen_server, cast, [self(), {init}]),
    {ok, #state{}}.


handle_call({check_acc,AppId,Token}, _From, State) ->
	?debug("1111111111111111111"),
	case fun_http_client:check_acc(AppId, Token) of
		{ok,Body}->
			?debug("1111111111111111111"),
			{reply, {ok,Body}, State};
		no_data->
			{reply, no_data, State}
	end;
handle_call({tourist_login,Machine_code}, _From, State) ->
	?debug("1111111111111111111"),
	case fun_http_client:tourist_login(Machine_code) of
		{ok,Body}->
			?debug("1111111111111111111"),
			{reply, {ok,Body}, State};
		no_data->
			{reply, no_data, State}
	end;
handle_call(_Request, _From, State) ->
%% 	{global,http_svr}, {check_acc,Acc,Token}
    Reply = ok,
	
    {reply, Reply, State}.

%% handle_cast({test}, State) ->
%% 	fun_http_client:test(),
%%     {noreply, State};

handle_cast(Msg, State) ->
	try
		fun_http_client:do_msg(Msg)
	catch 
		E:R -> ?log_error("fun_http_client  error E=~p,R=~p,stack=~p",[E,R,erlang:get_stacktrace()])
	end,	
    {noreply, State}.
%% 
%% handle_cast(_Msg, State) ->
%%  	{noreply, State}.
handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.



code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

test()->
    {ok, ConnPid} = gun:open("192.168.0.15", 8080),
    {ok, _Protocol} = gun:await_up(ConnPid),

    StreamRef = gun:get(ConnPid, "/user/tokenProving"),

    case gun:await(ConnPid, StreamRef) of
        {response, fin, _Status, _Headers} ->
            no_data;
        {response, nofin, _Status, _Headers} ->
            {ok, Body} = gun:await_body(ConnPid, StreamRef),
            io:format("~s~n", [Body])
    end.

start_http_client()->
	application:ensure_all_started(gun).

   

start_http() ->
	Ip =
		case application:get_env(http_ip) of
			{ok, Ip1} ->Ip1;
			_ ->{0,0,0,0}
		end,
	{ok, Port} = application:get_env(http_port),
	?debug("Port=~p",[Port]),
	Dispatch = cowboy_router:compile([
		  {'_', 
		   [
			{"/ddz_game/usr_login", handler_usr_login, []},
			{"/ddz_game/update_usrinfo", handler_update_usrinfo, []},
			{"/ddz_game/share_friend", handler_share_friend, []}	
		   ]
		  }
									 ]),
	TransOpts = [
				 {id,Ip},
				 {port, Port}
				],
	 cowboy:start_http(http, 100, TransOpts, [											
													{env, [{dispatch, Dispatch}]}
												   ]).
%% 	case Ret of
%% 		{ok, _} ->
%% 			http_sup:start_link();
%% 		Other -> ?log_error("start http server failed,ret=~p",[Other])
%% 	end.
